<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/4 0004
 * Time: 9:57
 * 用户、角色、权限
 *
 *
 */
namespace app\index\controller;

use app\index\controller\CommonController;
use app\index\model\Doctornurse;
use app\index\model\Sets;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Reader\Xls\MD5;
use think\Request;
use app\index\model\Data;
use think\Db;
use think\Cookie;

class Set extends CommonController{
    public function index(){
        //$all = Sets::all();

        $all =Db::query("select * from sets where id>=1 order by id asc ");

        $this->assign("sets",$all);

        return $this->fetch("Set/index");
    }
    public function receivesetdata(Request $request){
        $sets = new Sets();
        $lists = [

            ["id"=>3,"value"=>$request->param("device")],
            ["id"=>4,"value"=>$request->param("project")],
            ["id"=>5,"value"=>$request->param("treat")],
            ["id"=>16,"value"=>$request->param("from")],
            ["id"=>18,"value"=>$request->param("zhiliaoshi")],
            ["id"=>19,"value"=>$request->param("meirongshi")],
            ["id"=>22,"value"=>$request->param("yiliao1")],
            ["id"=>23,"value"=>$request->param("yiliao2")],
            ["id"=>24,"value"=>$request->param("meirong1")],
            ["id"=>25,"value"=>$request->param("meirong2")],
        ];
        $sets->saveAll($lists);
        echo "ok";

       // dd($request->param());

    }

    //排班表上传页面
    public function paiban(){
        $username = explode('-',Cookie::get('auth'))[0];
        $this->assign('username',$username);


        $this->assign("noticeType",0);

        if(request()->file('file')){
            // 获取表单上传文件 例如上传了001.jpg
            $file = request()->file('file');

            $fileName=$_FILES['file']['name'];
            if(!substr_count($fileName,'xlsx')){//文件格式不为xlsx

                $this->assign("noticeType",1);

                $all_data = $this->getExcel();
                $this->assign("all_data",$all_data);
                return $this->fetch("Set/paiban");
            }
            //dd(substr_count($fileName,'xlsx'));

            // 移动到框架应用根目录/public/uploads/ 目录下
            $info = $file->move(ROOT_PATH . 'public' . DS . 'uploads');
            if($info){
                // 成功上传后 获取上传信息,,,服务器操作系统不一样，后期上线需要更换！！！！
                $file_path = "./uploads/".$info->getSaveName();
                //打印出信息
                //dd(fileowner($file_path));
				
				$pb_file = "./uploads/pb.xlsx";
				//删除旧文件
				if(file_exists($pb_file)){
					unlink($pb_file);
				}
				
				copy($file_path,"./uploads/pb.xlsx");
				
				//删除中间的缓存文件
				unlink($file_path);
				
				$all_data = $this->getExcel();
				$this->assign("all_data",$all_data);
				return $this->fetch("Set/paiban");
            }else{
                // 上传失败获取错误信息
                echo $file->getError();
            }
        }else{
			
			$all_data = $this->getExcel();

			$this->assign("all_data",$all_data);

            //$this->assign("paiban_data",$doctornurse_arr);

            return $this->fetch("Set/paiban");
        }
    }

    //读取excel返回数组$path
    public function getExcel(){
		 //读取excel返回数组
		$reader = IOFactory::createReader('Xlsx');
		$reader->setReadDataOnly(TRUE);
		$spreadsheet = $reader->load("./uploads/pb.xlsx");

		//print_r(serialize($spreadsheet));
		
		$worksheet = $spreadsheet->getActiveSheet();
	// Get the highest row number and column letter referenced in the worksheet
		$highestRow = $worksheet->getHighestRow(); // e.g. 10
		$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
	// Increment the highest column letter
		$highestColumn++;

	//存储所有数据，后期一次性插入到数据库
		$all_arr = [];

		for ($row =1; $row <= $highestRow; ++$row) {
		
			//第一行头部不读取，直接跳转到第二行
			//if($row==1){continue;}
			//定义医生数组，后期转json格式
			$doctor_arr = [];
			$nurse_arr = [];
			$tmpstr = "";
			$d_date = "";
			for ($col = 'A'; $col != $highestColumn; ++$col) {
				
				$value = $worksheet->getCell($col . $row)->getValue();
			
				$all_arr[$row][$col] = $value;
			}
		}
	
		return $all_arr;
		/*

        $reader = IOFactory::createReader('Xlsx');
        $reader->setReadDataOnly(TRUE);
        $spreadsheet = $reader->load("$path");

        $worksheet = $spreadsheet->getActiveSheet();
// Get the highest row number and column letter referenced in the worksheet
        $highestRow = $worksheet->getHighestRow(); // e.g. 10
        $highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
// Increment the highest column letter
        $highestColumn++;

//存储所有数据，后期一次性插入到数据库
        $all_arr = [];

        for ($row = 1; $row <= $highestRow; ++$row) {
            //第一行头部不读取，直接跳转到第二行
            if($row==1){continue;}
            //定义医生数组，后期转json格式
            $doctor_arr = [];
            $nurse_arr = [];
            $tmpstr = "";
            $d_date = "";
            for ($col = 'A'; $col != $highestColumn; ++$col) {
                $value = $worksheet->getCell($col . $row)->getValue();

                switch ($col){
                    case 'A':
                        $d_date=$value;

                        if($row==2){
                            //取出单个数据查询数据库，如果存在就删除当月数据
                            $doctornurse = new Doctornurse();
                            $date_exist = $doctornurse::get(['d_date'=>$d_date]);
                            if($date_exist){
                                $year_month = substr($d_date,0,7);
                                Doctornurse::where('d_date','like',"%$year_month%")->delete();
                            }

                        }
                        break;
                    case 'B':
                        $doctor_arr["白班"]=$value;
                        break;
                    case 'C':
                        $doctor_arr["晚班"]=$value;
                        break;
                    case 'D':
                        $doctor_arr["正休"]=$value;
                        break;
                    case 'E':
                        $nurse_arr["白班"]=$value;
                        break;
                    case 'F':
                        $nurse_arr["晚班"]=$value;
                        break;
                    case 'G':
                        $nurse_arr["正休"]=$value;
                        break;
                }

            }

            $tmp_arr = ["d_date"=>"$d_date","d_doctor"=>json_encode($doctor_arr,JSON_UNESCAPED_UNICODE),"d_nurse"=>json_encode($nurse_arr,JSON_UNESCAPED_UNICODE)];
            array_push($all_arr,$tmp_arr);
        }
        return $all_arr;
		*/
    }

    //修改
    public function modify_paiban(Request $request){
        $d_id = $request->param();
        if(array_key_exists('d_id',$d_id)){
            $doctornurse = new Doctornurse();
            $result = $doctornurse->where("d_id",$d_id['d_id'])->find();
            $data = [];
            $data['d_id'] = $result['d_id'];
            $data['d_date'] = $result['d_date'];
            $data['d_doctor'] = json_decode($result['d_doctor'],JSON_UNESCAPED_UNICODE);
            $data['d_nurse'] = json_decode($result['d_nurse'],JSON_UNESCAPED_UNICODE);
            $data['d_status'] = $result['d_status'];

            $this->assign("data",$data);
            return $this->fetch("Set/modifypaiban");
        }else{
            echo json_encode(array("message"=>"d_id is must"));
        }
    }

    //接收修改数据
    public function receiveModifyPaiban(Request $request){
        $data = $request->param();
        if(array_key_exists("date",$data)){
            $doctornurse = new Doctornurse();
            $update = $doctornurse->save([
                'd_doctor'  => json_encode(["白班"=>$data['doctor_baiban'],"晚班"=>$data['doctor_wanban'],"正休"=>$data['doctor_zhengxiu']],JSON_UNESCAPED_UNICODE),
                'd_nurse'  => json_encode(["白班"=>$data['nurse_baiban'],"晚班"=>$data['nurse_wanban'],"正休"=>$data['nurse_zhengxiu']],JSON_UNESCAPED_UNICODE),
            ],['d_date'=>$data['date']]);

            if($update==1){
                $this->success("更新成功！");
            }else{
                $this->error("更新失败！");
            }
        }

    }

    //视图展示
    public function showcount(){
        $date = strtotime(date("Y-m-d"));

        //查询所有项目

        $project_resu = Sets::where('key',"project")->column('value');
        $project_resu_arr = explode("|",$project_resu[0]);
        foreach ($project_resu_arr as $key=>$value) {
            $project_resu_arr[$key]=explode('-',$value)[0];
        }


        $project_resu_arr_json = json_encode($project_resu_arr,JSON_UNESCAPED_UNICODE);

        //dd($project_resu_arr_json);


        //项目数组
        $project_arr = [];
        foreach($project_resu_arr as $k => $v){
            $result = Data::where('riqi',"$date")->where("buwei","like","%$v%")->count();
            array_push($project_arr,$result);
        }
        $project_arr_json = json_encode($project_arr,JSON_UNESCAPED_UNICODE);


        $mapdata = <<<EOF
 {
    color: ['#3398DB'],
    tooltip : {
        trigger: 'axis',
        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
            type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
        }
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis : [
        {
            type : 'category',
            data : $project_resu_arr_json,
            axisTick: {
                alignWithLabel: true,
            },
        }
    ],
    yAxis : [
        {
            type : 'value'
        }
    ],
    series : [
        {
            name:'次数',
            type:'bar',
            barWidth: '20%',
            data:$project_arr_json
        }
    ]
}
EOF;

        //echo $mapdata;

        $this->assign("mapdata",$mapdata);

        return $this->fetch("Set/count");
    }



    //统计当天项目情况
    public function count(Request $request){
        $data = $request->param();
        if(array_key_exists("date",$data)){
            $date = strtotime(str_replace(" ","",$data["date"]));

            //$date=strtotime($date);

            //查询所有项目
            $project_resu = Sets::where('key',"project")->column('value');
            $project_resu_arr = explode("|",$project_resu[0]);
            foreach ($project_resu_arr as $key=>$value) {
                $project_resu_arr[$key]=explode('-',$value)[0];
            }


            $project_resu_arr_json = json_encode($project_resu_arr,JSON_UNESCAPED_UNICODE);


            //项目数组
            $project_arr = [];
            foreach($project_resu_arr as $k => $v){
                $result = Data::where('riqi',"$date")->where("buwei","like","%$v%")->count();
                array_push($project_arr,$result);
            }
            $project_arr_json = json_encode($project_arr,JSON_UNESCAPED_UNICODE);




            $mapdata = <<<EOF
 {
    color: ['#3398DB'],
    tooltip : {
        trigger: 'axis',
        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
            type : 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
        }
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    xAxis : [
        {
            type : 'category',
            data : $project_resu_arr_json,
            axisTick: {
                alignWithLabel: true
            }
        }
    ],
    yAxis : [
        {
            type : 'value'
        }
    ],
    series : [
        {
            name:'次数',
            type:'bar',
            barWidth: '20%',
            data:$project_arr_json
        }
    ]
}
EOF;
            return $mapdata;
        }else{
            echo json_encode(array("message"=>"request error"));
        }

    }

    //今日时间段占用
    public function timeemploy(Request $request){


        $request_arr = $request->param();
        //今日时间
        //$time = strtotime(date("Y-m-d"));
        //$time = "1537545600";
        $time = array_key_exists("time",$request_arr)?strtotime($request_arr['time']):strtotime(date("Y-m-d"));


        $sets = Sets::get(4);
        $projects_arr = explode("|",$sets->value);
        foreach ($projects_arr as $key=>$value) {
            $projects_arr[$key]=explode('-',$value)[0];
        }


        //项目作为表头
        $this->assign("projects",$projects_arr);



        $time_arr = ["08:30","09:00","09:30","10:00","10:30","11:00","11:30","12:00","12:30","13:00","13:30","14:00","14:30","15:00","15:30","16:00","16:30","17:00","17:30","18:00","18:30","19:00","19:30"];

        //间隔5分钟
//        $arr=array();
//        for($i=9;$i<=18;$i++){
//            for($t=0;$t<60;$t+=5){
//                array_push($arr,str_pad($i,2,0,STR_PAD_LEFT).":".str_pad($t,2,0,STR_PAD_LEFT));
//            }
//        }
//        array_push($arr,"19:00");
//        $time_arr=$arr;


        //项目数组放入
        $time_arr_ar = [];


        //组装数据 ["时间"=>["项目"=>[name]]]
        foreach ($time_arr as $tk => $tv){
            foreach($projects_arr as $pk => $pv){
                $time_arr_ar[$tv][$pv]['data'] = [];
                $time_arr_ar[$tv][$pv]['colore'] = '';
            }
        }
        //dd($projects_arr);
        //dd($time_arr_ar);exit;

        $data = new Data();

        $tmp_projects=Db::query("select * from data where riqi='{$time}' order by d_id DESC ");
        //$tmp_projects=$data->where("riqi",$time)->select();




        //dd($time_arr_ar);
        //dd($tmp_projects);
        $coloreTab=array('#348888','#22BABB','#9EF8EE','#FA7F08','#F24405','#3B9ABF','#A1C7E0');
        $count=count($coloreTab);
        $ymd=date('Y-m-d',$time);
        $colore_arr=array();
        foreach($tmp_projects as $key=>$value){

            $item=strtotime($ymd." {$value['shijian']}");

            $spendtime=str_replace(array('小时','分钟'),'',$value['spendtime']);
            if($spendtime<10){$min=$spendtime*60;
            }else{$min=$spendtime;
            }

            $buwei=str_replace(array('[',']','"'),'',$value['buwei']);
            $qd=$item;
            $zd=$item+$min*60;
            $colore_arr[$key]['qd']=$qd;
            $colore_arr[$key]['zd']=$zd;
            $colore_arr[$key]['colore']=$coloreTab[$key%$count];
            $colore_arr[$key]['buwei']=$buwei;
        }


        foreach($time_arr_ar as $bk => $bv){
            $item_bk=strtotime($ymd." {$bk}");

            foreach ($bv as $ck => $cv){
                foreach ($tmp_projects as $dk => $dv){

                    $itme=str_replace(array('[',']','"'),'',$dv['buwei']);

                    if($ck==$itme&&$bk==$dv['shijian']){

                        array_push($time_arr_ar[$bk][$ck]['data'],$dv['name']);
                        array_push($time_arr_ar[$bk][$ck]['data'],$dv['d_id']);
                    };
                }

                //颜色赋予
                foreach ($colore_arr as $ckey=>$cvalue) {
                    if($cvalue['buwei']==$ck&&$cvalue['qd']<=$item_bk&&$cvalue['zd']>$item_bk){
                        $time_arr_ar[$bk][$ck]['colore']=$cvalue['colore'].";border-bottom:none;text-align:center;";
                    }
                }


            }
        }



//        dd($time_arr_ar);
//        exit;

        //使用上面的数组条件，查询like
//        foreach($time_arr_ar as $bk => $bv){
//            foreach ($bv as $ck => $cv){
//
//                $tmp_projects = Data::where("riqi",$time)->where("shijian",$bk)->where("buwei","like","%$ck%")->select();
//                if($tmp_projects){
//                    foreach ($tmp_projects as $dk => $dv){
//                        array_push($time_arr_ar[$bk][$ck],$dv['name']);
//
//                    }
//                }
//            }
//        }

//        $html='';
//        $bv_count=sizeof($bv);
//        for($i=0;$i<$bv_count;$i+=2){
//            if($i+2<$bv_count){
//                $html.="<div onclick='modify({$bv[$i+1]})'>$bv[$i],</div>";
//            }else{
//                $html.="<div onclick='modify({$bv[$i+1]})'>$bv[$i]</div>";
//            }
//        }


        //dd($time_arr_ar);exit;

        $this->assign("data",$time_arr_ar);

        return $this->fetch("Set/timeemploy");

        /*
        $tmp_projects = Data::where("riqi",$time)->where("shijian",$tv)->select();
        foreach($tmp_projects as $k => $v){
            array_push($time_arr_ar[$tv][$pv],$v['name']);
        }
        */
    }

    //今日预约表弹出式添加
    public function tcadd(Request $request){

        $item = $request->param("item");
        $date = $request->param("date");
        $time = explode(":",$request->param("time"));



        $this->assign("time",$time);
        $this->assign("date",$date);
        $this->assign("item",$item);


        $setsobj = new Sets();

        $data = $setsobj::all();

        $data_array = [];
        $i = 0;
        foreach ($data as $k => $v){
            $data_array[$i]['id'] = $v['id'];
            $data_array[$i]['key'] = $v['key'];
            $data_array[$i]['value'] = explode("|",$v['value']);
            $data_array[$i]['status'] = $v['status'];
            $i++;
        }


        //dd($data_array);
        $this->assign("data",$data_array);

        return $this->fetch("Set/tcadd");
    }
	
	
	//测试
	public function testtt(Request $request){
		/*
		 //读取excel返回数组
		$reader = IOFactory::createReader('Xlsx');
		$reader->setReadDataOnly(TRUE);
		$spreadsheet = $reader->load("./uploads/pb.xlsx");

		$worksheet = $spreadsheet->getActiveSheet();
	// Get the highest row number and column letter referenced in the worksheet
		$highestRow = $worksheet->getHighestRow(); // e.g. 10
		$highestColumn = $worksheet->getHighestColumn(); // e.g 'F'
	// Increment the highest column letter
		$highestColumn++;

	//存储所有数据，后期一次性插入到数据库
		$all_arr = [];

		for ($row = 1; $row <= $highestRow; ++$row) {
			//第一行头部不读取，直接跳转到第二行
			if($row==1){continue;}
			//定义医生数组，后期转json格式
			$doctor_arr = [];
			$nurse_arr = [];
			$tmpstr = "";
			$d_date = "";
			for ($col = 'A'; $col != $highestColumn; ++$col) {
				$value = $worksheet->getCell($col . $row)->getValue();

				echo $value."-";
			}

			//$tmp_arr = ["d_date"=>"$d_date","d_doctor"=>json_encode($doctor_arr,JSON_UNESCAPED_UNICODE),"d_nurse"=>json_encode($nurse_arr,JSON_UNESCAPED_UNICODE)];
			//array_push($all_arr,$tmp_arr);
		}
		*/
		
		//时长数组
		$time_arr = [];
		
		//项目
		$project_arr = [];
		
		//设备
		$shebei_arr = [];
		
		//医生
		$doctor_arr = [];
		
		//护士
		$nurse_arr = [];
		
		//治疗室
		$zhiliaoshi = [];
		
		//返回数组
		$allData = [];
		
		$time = $request->param("time");
		$date = $request->param("date");
		
		
		
		$date = strtotime(str_replace(" - ","","$date"));
		$result = Data::all(["riqi"=>$date,"shijian"=>"$time"]);
		foreach($result as $k => $v){
			array_push($time_arr,$v["shijian"]);
			array_push($project_arr,str_replace('"]','',str_replace('["','',$v["buwei"])));
			array_push($shebei_arr,str_replace('"]','',str_replace('["','',$v["shebei"])));
			array_push($doctor_arr,str_replace('"]','',str_replace('["','',$v["doctor"])));
			array_push($nurse_arr,str_replace('"]','',str_replace('["','',$v["meirongshi"])));
			array_push($zhiliaoshi,str_replace('"','',str_replace('"','',$v["zhiliaoshi"])));
		}
		
		$allData["time_arr"] = $time_arr;
		$allData["project_arr"] = $project_arr;
		$allData["shebei_arr"] = $shebei_arr;
		$allData["doctor_arr"] = $doctor_arr;
		$allData["nurse_arr"] = $nurse_arr;
		$allData["zhiliaoshi"] = $zhiliaoshi;
		
		echo json_encode($allData,JSON_UNESCAPED_UNICODE );
	}

    //添加帐号
    public  function  adduser(){
        if(!empty($_REQUEST['user'])){
            $user=input('user');
            $password=md5(input('password'));
            Db::query("insert into admin (uname,upass,urole)values('{$user}','{$password}',2)");
            return 1;
        }

        $data=DB::query("select id,uname from admin where id>1");
        $this->assign('data',$data);

        return $this->fetch("Set/adduser");
        //$this->redirect("/index/login/adduser");
    }
    //删除帐号
    public function deleteuser(){
        $id=input('id');
        Db::query("delete from admin where id='{$id}'");
        return 1;
    }
    //修改密码
    public  function updatepass(){
        if(!empty($_REQUEST['password'])){
            $password=md5(input('password'));
            if(!empty($_REQUEST['id'])){
                $id=input('id');
                Db::query("update admin set upass='{$password}' where id='{$id}'");
            }else{
                $user=explode('-',cookie("auth"))[0];
                Db::query("update admin set upass='{$password}' where uname='{$user}'");
            }

            return 1;
        }

        $data=['id'=>0];
        if(!empty($_REQUEST['id'])){
            $id=input('id');
            $uname=input('uname');
            $data=['id'=>$id,'uname'=>$uname];
        }
        $this->assign('data',$data);

        return $this->fetch("Set/updatepass");
    }


}
